package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 *  
 * MD5工具类 
 * @author jiankang
 * @date 2013-11-25
 * @version 1.0
 */
public class MD5Utils {

	public static String getFileMD5String(File file) throws IOException,
			NoSuchAlgorithmException {
		MessageDigest messagedigest = MessageDigest.getInstance("MD5");
		InputStream fis;
		fis = new FileInputStream(file);
		byte[] buffer = new byte[4096];
		int numRead = 0;
		while ((numRead = fis.read(buffer)) > 0) {
			messagedigest.update(buffer, 0, numRead);
		}
		fis.close();
		return BytesUtil.bytes2Hex(messagedigest.digest());
	}


    public static String getStringDigest(String text){
        try{
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");
            byte[] buf = text.getBytes("utf-8");
            messagedigest.update(buf, 0, buf.length);
            return BytesUtil.bytes2Hex(messagedigest.digest()).toLowerCase();
        }catch(Exception ex){
            throw new RuntimeException(ex);
        }
    }


	
	public static String getIdMD5Digest(long id , byte[] random ) {
		try{
			MessageDigest messagedigest = MessageDigest.getInstance("MD5");
			messagedigest.update(random, 0, random.length);
			byte[] data = BytesUtil.long2Bytes(id);
			messagedigest.update(data, 0, data.length);
			return BytesUtil.bytes2Hex(messagedigest.digest());
		}catch(Exception ex){
			throw new RuntimeException(ex);
		}
	}
	

	
	public static String getMD5Digest(long id ,byte[] token, byte[] key ) {

		try{
			MessageDigest messagedigest = MessageDigest.getInstance("MD5");
			byte[] data = BytesUtil.long2Bytes(id);
			messagedigest.update(data, 0, data.length);
			messagedigest.update(token, 0, token.length);
			messagedigest.update(key, 0, key.length);
			return BytesUtil.bytes2Hex(messagedigest.digest());
		}catch(Exception ex){
			throw new RuntimeException(ex);
		}
	}

}
